#!/usr/bin/env python
## temp file, will be removed

import sys
import os
import zipfile
import urllib

PLATFORMS = {
    'esp32' : {
        'toolchain': {
            'esp32-toolchain': {
                'url': 'https://dl.espressif.com/dl/xtensa-esp32-elf-linux64-1.22.0-80-g6c4433a-5.2.0.tar.gz',
                'version': '5.2.0',
                'type': 'tar.gz'
            },
            'esp-idf': {
                'url': 'https://dl.espressif.com/dl/esp-idf/releases/esp-idf-v3.2.2.zip',
                'version': 'v3.2.2',
                'type': 'zip'
            }
        }
    }
}

CURRENT_PLATFORM = 'esp32'

def intsallTools():
    os.system("sudo apt-get install gcc git wget make libncurses-dev flex bison gperf python python-pip python-setuptools python-serial python-cryptography python-future python-pyparsing -y")


def tryMkdir(dir):
    try:
        os.makedirs(dir)
        return True
    except:
        return False


def progressbar(blocknum, blocksize, totalsize):
    bar_length = 50
    percent = 100.0 * blocknum * blocksize / totalsize
    hashes = '#' * int(percent / 100 * bar_length)
    spaces = ' ' * (bar_length - len(hashes))
    sys.stdout.write("\rDownloading: [%s] %.1f%%"%(hashes + spaces, percent))
    sys.stdout.flush()
    if int(percent) >= 100:
        print("\n...Done!")


def prepareToolchainZip(toolName, tool):
    print('Downloading %s, version %s, URL: %s' % (toolName, tool['version'], tool['url']))
    downloadPath = 'downloads/%s-%s.zip' % (toolName, tool['version'])
    page = urllib.urlopen(tool['url'])
    file_size = int(page.info()['Content-Length'])
    page.close()

    # Avoid re-download
    if os.path.isfile(downloadPath) and os.path.getsize(downloadPath) == file_size:
        print('Using cached: %s' % downloadPath)
        pass
    else:
        urllib.urlretrieve(tool['url'], downloadPath, progressbar)
    
    unpackPath = 'toolchain/%s' % (toolName)
    print('Unpacking to %s' % unpackPath)
    with zipfile.ZipFile(downloadPath) as zipf:
        zipf.extractall(unpackPath)
    return True


def perpareToolchain():
    intsallTools()
    plat = PLATFORMS[CURRENT_PLATFORM]
    toolchain = plat['toolchain']
    tryMkdir('toolchain')
    tryMkdir('downloads')
    for toolName in toolchain.keys():
        tool = toolchain[toolName]
        result = False
        if tool['type'] == 'zip':
            result = prepareToolchainZip(toolName, tool)
        if result:
            print('..OK!')
        elif tool['type'] == 'tar.gz':
            print('Downloading %s, version %s, URL: %s' % (toolName, tool['version'], tool['url']))
            os.system('wget  -P downloads ' + tool['url'])
            print('..OK!')
            os.system('cd ./toolchain;tar -xzf ./../downloads/xtensa-esp32-elf-linux64-1.22.0-80-g6c4433a-5.2.0.tar.gz')
        else:
            print('...Failed!')
            return False
    print('Toolchain is ready!')


def dataToU8Array(d, arrName):
    ret = 'const uint8_t %s[] =  {' % arrName
    for i in range(0, len(d)):
        if (i % 16 == 0):
            ret += '\n'
        ret += '0x%02x, ' % ord(d[i])
    ret += '};\n\n'
    return ret


def generate():
    QUICKJS_FILES = [
        'quickjs', 'libregexp', 'libunicode', 'cutils', 'quickjs-libc'
    ]
    QUICKJS_FILES += [
        'qjs', 'repl'
    ]
    print('Generating header file gen_js.h from builtin-js directory.')
    js = ''
    for fn in os.listdir('builtin-js'):
        if (not fn.startswith('.')) and fn.endswith('.js'):
            print(fn)
            with open('builtin-js/' + fn, 'rb') as f:
                d = f.read() + '\x00'
            js += dataToU8Array(d, 'js_%s' % fn.split('.')[0])
    with open('platform/esp32/main/__generated/gen_js.h', 'wb') as f:
        f.write(js)


def build():
    pass

    
def startShellInEnvironment():
    cwd = os.getcwd()
    os.environ['IDF_PATH'] = cwd + '/toolchain/esp-idf/esp-idf-v3.2.2'
    os.environ['PATH']+=':'+cwd+'/toolchain/xtensa-esp32-elf/bin'
    print('....done')
    os.system('bash')


def usage():
    print("""
Usage: python build.py COMMAND [OPTIONS]

Available commands:
    prepare-toolchain   Download and install toolchain.
    generate            Generate files for build.
    build               Build quickmcu.
    env                 Start a shell in build environment.

""")


action = ''
os.environ['IDF_PATH'] = os.getcwd() + '/toolchain/esp-idf/esp-idf-v3.2.2'
if len(sys.argv) >= 2:
    action = sys.argv[1]
if action == 'prepare-toolchain':
    perpareToolchain()
elif action == 'generate':
    generate()
elif action == 'build':
    build()
elif action == 'env':
    startShellInEnvironment()
else:
    usage()
